package com.youi.web;

import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Operationlog;
import com.youi.entity.Sysuser;
import com.youi.entity.vo.Userorderrecord;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.OperationlogService;
import com.youi.service.SysuserService;
import com.youi.service.UserorderrecordService;
import com.youi.util.CommonInfoUtil;
import com.youi.util.JedisUtils;
import com.youi.util.JsonUtil;
import com.youi.util.MD5;
import com.youi.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页信息控制层
 *
 * @author XJY
 */
@Controller
public class TopController extends HttpRequestManage {

    @Autowired
    private SysuserService sysuserService;
    @Autowired
    private OperationlogService operationlogService;
    @Autowired
    private UserorderrecordService userorderrecordService;

    /**
     * I-0
     * 系统管理员登陆
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("sysuserLogin")
    public String delUserByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        String account = getString("account", request);
        String password = getString("password", request);
        String validateCode = getString("validateCode", request);
        String sessionCode = (String) HttpSessionManage.getAttribute(request, "validateCode");
        if (sessionCode == null || sessionCode.length() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "验证码错误请刷新一下验证码");
        }
        if (!sessionCode.equalsIgnoreCase(validateCode)) {
            return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "验证码错误");
        }
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("account", account);
        prams.put("password", MD5.getPwdMd5(password));
        Sysuser sysuser = sysuserService.getByParam(prams);
        if (sysuser == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "账号不存在或密码错误");
        }
        if (sysuser.getOpenState() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "账户已停用,请联系平台客服!");
        }
        sysuser.setGmtLastLogin(new Date());
        sysuserService.saveOrUpdate(sysuser);
        sysuserService.getSysuserMsg(sysuser);
        operationlogService.saveOrUpdate(new Operationlog(sysuser.getId(), null, null, sysuser.getAccount() + "登陆"));
        HttpSessionManage.setAttribute(request, SessionKey.SYSUSER, sysuser);
        //保存会话消息到redis
        StringBuffer sb = new StringBuffer().
                append(SessionKey.SYSUSER).append(":").
                append(HttpSessionManage.getSessionId(request));
        String key = sb.toString();
        if (!JedisUtils.exists(key)) {
            JedisUtils.setObject(sb.toString(), sysuser, 1800);
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", sysuser);
    }

    /**
     * I-1
     * 管理员退出登录
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/sysuserLoginOut")
    public String sysuserLoginOut(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        HttpSessionManage.removeAttribute(request, SessionKey.SYSUSER);

        //移除redis中的会话消息
		StringBuffer sb = new StringBuffer().
				append(SessionKey.SYSUSER).append(":").
				append(HttpSessionManage.getSessionId(request));
		String key = sb.toString();
		if (JedisUtils.exists(key)) {
			JedisUtils.del(key);
		}
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作成功");
    }

    /**
     * I-2
     * 查询当前登录管理员信息
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getLoginSysuser")
    public String getLoginSysuser(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        sysuserService.getSysuserMsg(sysuser);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", sysuser);
    }

    /**
     * I-3
     * 修改当前登录管理员密码
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/editLoginSysuserPassword")
    public String editLoginSysuserPassword(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        //旧密码
        String oldPassword = getString("oldpassword", request);
        //新密码
        String newPassword = getString("newpassword", request);
        if (!MD5.getPwdMd5(oldPassword).equals(sysuser.getPassword())) {
            System.out.println(MD5.getPwdMd5(oldPassword) + "=======================" + sysuser.getPassword());
            return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "旧密码输入不正确");
        }
        sysuser.setPassword(MD5.getPwdMd5(newPassword));
        sysuser.setGmtModify(new Date());
        sysuserService.saveOrUpdate(sysuser);
        HttpSessionManage.setAttribute(request, SessionKey.SYSUSER, sysuser);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * I-4
     * 修改当前登录管理员信息
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/editLoginSysuser")
    public String editLoginSysuser(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);

        //头像
        String img = optString("img", request);
        if (img != null && img.length() > 0) {
            sysuser.setImg(img);
        }
        //姓名
        String name = optString("name", request);
        if (name != null && name.length() > 0) {
            sysuser.setName(name);
        }
        //邮箱
        String email = optString("email", request);
        if (email != null && email.length() > 0) {
            sysuser.setEmail(email);
        }
        //备注
        String remark = optString("remark", request);
        if (remark != null && remark.length() > 0) {
            sysuser.setRemark(remark);
        }
        sysuser.setGmtModify(new Date());
        sysuserService.saveOrUpdate(sysuser);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * I-124
     * 查询总资金流水报表
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getUserorderrecord")
    public String getUserorderrecord(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        String start = optString("start", request);
        String end = optString("end", request);
        String merWithStart = optString("merWithStart", request);
        String merWithEnd = optString("merWithEnd", request);
        String platWithStart = optString("platWithStart", request);
        String platWithEnd = optString("platWithEnd", request);
        String orderNo = optString("orderNo", request);
        String merchantPms = optString("merchantPms", request);
        String goodsPms = optString("goodsPms", request);
        String goosTypeNo = optString("goosTypeNo", request);
        String phone = optString("phone", request);
        Long leaderId = optLong("leaderId", request);
        String receStart = optString("receStart", request);
        String receEnd = optString("receEnd", request);
        String unfreezeStart = optString("unfreezeStart", request);
        String unfreezeEnd = optString("unfreezeEnd", request);
        Integer status = optInteger(Common.STATUS, request);
        Integer platformStatus = optInteger("platformStatus", request);
        Integer merchantStatus = optInteger("merchantStatus", request);
        String goodsIds = userorderrecordService.getGoodsIds(goosTypeNo);
        Long merchantId = null;
        if (sysuser.getMerchantId() != null) {
            merchantId = sysuser.getMerchantId();
        }
        List<Userorderrecord> userorderrecordList = userorderrecordService.getUserorderrecordList(merchantId, start, end, merWithStart, merWithEnd, platWithStart, platWithEnd, orderNo, merchantPms, goodsPms, goodsIds, phone, leaderId, receStart, receEnd, unfreezeStart, unfreezeEnd, status, platformStatus, merchantStatus, (pageIndex - 1) * pageNum, pageNum);
        if (userorderrecordList == null || userorderrecordList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        Integer pageCount = userorderrecordService.getUserorderrecordCount(merchantId, start, end, merWithStart, merWithEnd, platWithStart, platWithEnd, orderNo, merchantPms, goodsPms, goodsIds, phone, leaderId, receStart, receEnd, unfreezeStart, unfreezeEnd, status, platformStatus, merchantStatus);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);            //pageIndex     查询页数
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, userorderrecordList);        //jsonObjectList json对象集合
        userorderrecordService.getUserorderrecordMsg(userorderrecordList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * I-125
     * 导出总资金流水报表excel
     */
    @ResponseBody
    @RequestMapping("toExcelUserorderrecord")
    public String toExcelUserorderrecord(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        String start = optString("start", request);
        String end = optString("end", request);
        String merWithStart = optString("merWithStart", request);
        String merWithEnd = optString("merWithEnd", request);
        String platWithStart = optString("platWithStart", request);
        String platWithEnd = optString("platWithEnd", request);
        String orderNo = optString("orderNo", request);
        String merchantPms = optString("merchantPms", request);
        String goodsPms = optString("goodsPms", request);
        String goosTypeNo = optString("goosTypeNo", request);
        String phone = optString("phone", request);
        Long leaderId = optLong("leaderId", request);
        String receStart = optString("receStart", request);
        String receEnd = optString("receEnd", request);
        String unfreezeStart = optString("unfreezeStart", request);
        String unfreezeEnd = optString("unfreezeEnd", request);
        Integer status = optInteger(Common.STATUS, request);
        Integer platformStatus = optInteger("platformStatus", request);
        Integer merchantStatus = optInteger("merchantStatus", request);
        String goodsIds = userorderrecordService.getGoodsIds(goosTypeNo);
        Long merchantId = null;
        if (sysuser.getMerchantId() != null) {
            merchantId = sysuser.getMerchantId();
        }
        List<Userorderrecord> userorderrecordList = userorderrecordService.getUserorderrecordList(merchantId, start, end, merWithStart, merWithEnd, platWithStart, platWithEnd, orderNo, merchantPms, goodsPms, goodsIds, phone, leaderId, receStart, receEnd, unfreezeStart, unfreezeEnd, status, platformStatus, merchantStatus, null, null);
        if (userorderrecordList == null || userorderrecordList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorderrecordService.getUserorderrecordMsg(userorderrecordList);
        modelMap.put("url", userorderrecordService.toExcelUserorderrecord(request, userorderrecordList));
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");    //jsonObjectList json对象集合
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }
}
